package com.xudow.app.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.base.OrderPayments;
import com.activeshare.edu.ucenter.models.coupons.CouponsWithOther;
import com.activeshare.edu.ucenter.models.order.AgencyOrderItems;
import com.alipay.sdk.app.PayTask;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.pay.alipay.Alipay;
import com.xudow.app.pay.alipay.PayResult;
import com.xudow.app.pay.wx.WxPay;
import com.xudow.app.ui.task.CouponListTask;
import com.xudow.app.ui.task.PaymentCreateTask;
import com.xudow.app.ui.task.PaymentUpdateTask;
import com.xudow.app.ui.user.OrdersActivity;
import com.xudow.app.util.Maps;
import com.xudow.app.util.PriceUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * 支付Activity
 *
 * @author lukecheng
 */
public class PayActivity extends BaseActivity implements DialogInterface.OnClickListener {
    private static final String TAG = makeLogTag(PayActivity.class);

    private RadioButton wxPayRadioBtn,
            alipayRadioBtn;
    private RelativeLayout root;
    private TextView orderPriceView;
    private LinearLayout couponsLayout;
    private Spinner couponSpinner;

    private int currectPayMethod = R.id.pay_alipay_radio_btn; //默认为支付宝支付

    //订单
    private Long orderId;
    private float orderPrice;
    private OrderPayments payment;
    private List<AgencyOrderItems> orderItemses;

    private PaymentCreateTask paymentCreateTask;
    private PaymentUpdateTask paymentUpdateTask;

    private CouponListTask couponListTask;
    private List<CouponsWithOther> coupons;
    private List<String> couponNames;
    private ArrayAdapter<String> couponsAdapter;

    private PayStatusPopup popup;

    //private String itemIds; //订单产品ids
   // private String courseHours; //订单产品课时s

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);

        wxPayRadioBtn = (RadioButton) findViewById(R.id.pay_wx_radio_btn);
        alipayRadioBtn = (RadioButton) findViewById(R.id.pay_alipay_radio_btn);
        root = (RelativeLayout) findViewById(R.id.root);
        orderPriceView = (TextView) findViewById(R.id.order_price);
        couponsLayout = (LinearLayout) findViewById(R.id.coupons_layout);
        couponSpinner = (Spinner) findViewById(R.id.coupons);
       // couponSpinner.setAdapter(new ArrayAdapter<String>());
        couponSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position > 0) {
                    Integer couponValue = coupons.get(position).getCouponType().getValue();

                    //实际价格不能少于或者等于优惠券价格
                    if (orderPrice < couponValue) {
                        return;
                    }

                    float newCoursePrice = orderPrice - couponValue;
                    orderPriceView.setText("￥" + PriceUtil.format(newCoursePrice));
                } else {
                    orderPriceView.setText("￥" + PriceUtil.format(orderPrice));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        Intent intent = getIntent();
        orderPrice = Float.parseFloat(intent.getStringExtra("orderPrice"));
        //itemIds = intent.getStringExtra("item_ids");
        //courseHours = intent.getStringExtra("course_hours");

        orderPriceView.setText("￥" + PriceUtil.format(orderPrice));

        showLodingDialog(getString(R.string.loading));

        HashMap couponParams = Maps.newHashMap();
        couponParams.put("unused", "true");

        couponListTask = new CouponListTask(this, couponListTaskHandler);
        couponListTask.execute(couponParams);
    }

    @Override
    protected void onResume() {
        super.onResume();

        Intent intent = getIntent();
        orderId = intent.getLongExtra("orderId", 0L);

        XApplication application = (XApplication) getApplication();
        application.currentOrderId = orderId;
    }

    public void onBackBtnClick(View view) {
        finish();
    }

    /**
     * 支付选项选择
     *
     * @param view
     */
    public void onPayOptionSelect(View view) {
        wxPayRadioBtn.setChecked(false);
        alipayRadioBtn.setChecked(false);

        ((RadioButton) view).setChecked(true);

        currectPayMethod = view.getId();
    }

    public void onPayLayoutSelect(View view) {
        wxPayRadioBtn.setChecked(false);
        alipayRadioBtn.setChecked(false);

        if (view.getId() == R.id.wx_layout) {
            currectPayMethod = R.id.pay_wx_radio_btn;
            wxPayRadioBtn.setChecked(true);
        } else if (view.getId() == R.id.alipay_layout) {
            currectPayMethod = R.id.pay_alipay_radio_btn;
            alipayRadioBtn.setChecked(true);
        }
    }

    /**
     * 支付按钮点击事件
     *
     * @param view
     */
    public void pay(View view) {
        if (currectPayMethod == R.id.pay_wx_radio_btn) {
            //如果是微信支付
            if (!WxPay.isWXAppInstalledAndSupported(this)) {
                Toast.makeText(this, getString(R.string.wx_app_required), Toast.LENGTH_LONG).show();
                return;
            }
        }

        payPrepare();
    }

    /**
     * 生成支付信息
     */
    private void payPrepare() {
        showLodingDialog(getString(R.string.processing));

        paymentCreateTask = new PaymentCreateTask(this, paymentCreateTaskHandler);

        HashMap<String, String> params = Maps.newHashMap();
        params.put("order_id", "" + orderId);
        params.put("pay_type", "1"); //1：网上支付 2：到机构支付

        //1：微信钱包 2：支付宝 3：银联
        int payMethod = 0;
        if (R.id.pay_wx_radio_btn == currectPayMethod) {
            payMethod = 1;
        } else if (R.id.pay_alipay_radio_btn == currectPayMethod) {
            payMethod = 2;
        }
        params.put("pay_method", "" + payMethod);

        float actualOrderPrice = orderPrice;
        // TODO
        //是否使用优惠券
        int couponPosition = couponSpinner.getSelectedItemPosition();
        if (couponPosition >= 1) {
            CouponsWithOther coupon = coupons.get(couponPosition);

            //实际价格不能少于或者等于优惠券价格
            if (actualOrderPrice >= coupon.getCouponType().getValue()) {
                params.put("coupon_id", "" + coupon.getId());
                actualOrderPrice -= coupon.getCouponType().getValue();
            }
        }

        params.put("pay_amount", "" + actualOrderPrice);


        payment=null;//每次点击payment刷新
        paymentCreateTask.execute(params);
    }

    /**
     * 生成支付方式Handler
     */
    private Handler paymentCreateTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (PaymentCreateTask.SUCCESS == msg.what) {
                payment = (OrderPayments) msg.getData().get("payment");

                XApplication application = (XApplication) getApplication();
                application.currentOrderPayments = payment;
             //TODO 测试支付码是否重复getMyApp().makeToast("支付码:"+payment.getTransactionCode());

                AgencyOrderItems[] orderItemArr = (AgencyOrderItems[]) msg.getData().get("orderItems");

                orderItemses = new ArrayList<AgencyOrderItems>();
                orderItemses.addAll(Arrays.asList(orderItemArr));

                if (payment.getPayAmount() == 0) {
                    //如果是0元
                    //如果是支付成功，首先修改支付信息
                    HashMap<String, String> params = Maps.newHashMap();
                    params.put("payment_id", "" + payment.getId());
                    params.put("pay_status", "1"); //0：支付失败 1：支付成功 2:等待支付结果

                    paymentUpdateTask = new PaymentUpdateTask(PayActivity.this, paymentUpdateTaskHandler);
                    paymentUpdateTask.execute(params);
                } else {
                    //网上支付
                    if (R.id.pay_alipay_radio_btn == currectPayMethod) {
                        //支付宝
                        alipayCheck();
                    } else {
                        //微信
                        wxPay();
                    }
                }
            } else {
                String message = getString(R.string.process_fail);
                getMyApp().makeToast(message);
            }
        }
    };

    /**
     * 使用支付宝支付
     */
    private void alipay() {
        Alipay alipay = new Alipay();

        // 订单
        String orderName = orderItemses.get(0).getName();
        String orderDesc = orderItemses.get(0).getDescription();

        //if (StringUtils.isEmpty(orderDesc.trim())) {
        orderDesc = orderName;
        //}

        String orderInfo = alipay.getOrderInfo(orderName, orderDesc,
                "" + payment.getPayAmount(),
                payment.getTransactionCode());


        // 对订单做RSA 签名
        String sign = alipay.sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + alipay.getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask pay = new PayTask(PayActivity.this);
                // 调用支付接口，获取支付结果
                String result = pay.pay(payInfo);

                Message msg = new Message();
                msg.what = Alipay.SDK_PAY_FLAG;
                msg.obj = result;
                alipayPayHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler alipayPayHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Alipay.SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    String message;
                    int iconRes;

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //如果是支付成功，首先修改支付信息
                        HashMap<String, String> params = Maps.newHashMap();
                        params.put("payment_id", "" + payment.getId());
                        params.put("pay_status", "1"); //0：支付失败 1：支付成功 2:等待支付结果

                        paymentUpdateTask = new PaymentUpdateTask(PayActivity.this, paymentUpdateTaskHandler);
                        paymentUpdateTask.execute(params);
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            message = "支付结果确认中";
                            iconRes = R.mipmap.ico_cry_face;
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            //用户取消支付
                            return;
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            message = "支付失败";
                            iconRes = R.mipmap.ico_cry_face;
                        }

                        popup = new PayStatusPopup(PayActivity.this, iconRes, message);
                        popup.showAtLocation(root, Gravity.CENTER, 0, 0);

                        gotoMyOrdersHandler.sendEmptyMessageDelayed(1, 3000);
                    }

                    break;
                }
                case Alipay.SDK_CHECK_FLAG: {
                    if (null != msg.obj) {
                        if (((Boolean) msg.obj)) {
                            alipay();
                        } else {
                            Toast.makeText(PayActivity.this, getString(R.string.alipay_app_required), Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * check whether the device has authentication alipay account.
     * 查询终端设备是否存在支付宝认证账户
     */
    private void alipayCheck() {
        /*
        Runnable checkRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask payTask = new PayTask(PayActivity.this);
                // 调用查询接口，获取查询结果
                boolean isExist = payTask.checkAccountIfExist();

                Message msg = new Message();
                msg.what = Alipay.SDK_CHECK_FLAG;
                msg.obj = isExist;
                alipayPayHandler.sendMessage(msg);
            }
        };

        Thread checkThread = new Thread(checkRunnable);
        checkThread.start();
        */
        alipay();
    }

    /**
     * 更新支付信息Handler
     */
    private Handler paymentUpdateTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (PaymentUpdateTask.SUCCESS == msg.what) {
                String message = "支付成功";
                int iconRes = R.mipmap.icon_green_check;

                popup = new PayStatusPopup(PayActivity.this, iconRes, message);
                popup.showAtLocation(root, Gravity.CENTER, 0, 0);

                //3秒钟后弹窗消失，跳转订单列表或详情
                gotoMyOrdersHandler.sendEmptyMessageDelayed(0, 3000);
                //TODO

                /*Intent intent=new Intent(PayActivity.this,OrdersActivity.class);
                startActivity(intent);*/
            }
        }
    };

    /**
     * 跳转到订单列表
     */
    private Handler gotoMyOrdersHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            XApplication application = (XApplication) getApplication();
            application.closeChainActivities();

            if (msg.what > 0) {
                if (null != popup) {
                    popup.dismiss();
                    popup = null;
                }
            } else {
                /*if (1<orderItemses.size()) {//课程数量大于1 跳转到已支付订单页面
                    Intent intent = new Intent(getApplicationContext(), OrdersActivity.class);
                    intent.putExtra("orderstate",0);
                    startActivity(intent);
                    finish();
                }else{//课程数量=1跳转到订单详情页面*/
                    dialog("是否现在为学生选座");
                //}
            }
        }
    };
    /**
     * 对话框
     */
    protected void dialog(String title) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(title);  builder.setTitle("提示");
        builder.setPositiveButton("确认", PayActivity.this);
        builder.setNegativeButton("取消", PayActivity.this);
        builder.create().show();
    }

    /**
     * 优惠券加载Handler
     */
    private Handler couponListTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (CouponListTask.SUCCESS == msg.what) {
                CouponsWithOther[] dataArr = (CouponsWithOther[]) msg.getData().getSerializable("coupons");

                coupons = new ArrayList<CouponsWithOther>();

                CouponsWithOther emptyCoupon = new CouponsWithOther();
                emptyCoupon.setCode(getString(R.string.select_prompt));
                emptyCoupon.setId(0L);

                coupons.add(emptyCoupon);

                coupons.addAll(Arrays.asList(dataArr));

                couponNames = new ArrayList<String>();
                for (CouponsWithOther c : coupons) {
                    if (null != c.getCouponType()) {
                        couponNames.add(c.getCouponType().getName() + "\t(价值￥" + c.getCouponType().getValue() + ")");
                    } else {
                        couponNames.add(c.getCode());
                    }
                }

                couponsAdapter = new ArrayAdapter<String>(PayActivity.this,
                        R.layout.item_spinner, couponNames);
                couponSpinner.setAdapter(couponsAdapter);

                if (coupons.size() > 1) {
                    couponsLayout.setVisibility(View.VISIBLE);
                }
            }
        }
    };

    /**
     * 微信支付
     */
    private void wxPay() {
        // 订单
        String orderName = orderItemses.get(0).getName();
        String orderDesc = orderItemses.get(0).getDescription();

        //if (StringUtils.isEmpty(orderDesc.trim())) {
        orderDesc = orderName;
        //}

        //注册退出
        XApplication application = (XApplication) getApplication();
        application.addChainActivity(this);

        /**
         * 微信支付的金额是以分为单位
         */
        int payAmount = (int) (payment.getPayAmount() * 100);
        Log.e("wxPay: ",payAmount+"--"+orderDesc+payment.getTransactionCode() );
        WxPay wxPay = new WxPay(this,
                "" + payAmount,
                orderDesc,
                payment.getTransactionCode());
        wxPay.start();
    }

    /**
     * 对话框监听处理
     * @param dialog which=-1为确认
     * @param which
     */
    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (-1==which){
                //TODO 跳转到已支付订单列表
            Intent intent = new Intent(getApplicationContext(), OrdersActivity.class);
            intent.putExtra("orderstate",0);
            startActivity(intent);

        }
            dialog.dismiss();
        finish();
    }
}
